package com.seek.configuation;

import com.seek.service.impl.MyUserDetailsServiceImpl;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;

import javax.annotation.Resource;


/**
 * Description: oauth2认证服务器配置
 * @author seek412
 * @version v1.0
 * @date 2018-09-22
 */
@Configuration
@EnableAuthorizationServer
public class Oauth2ServerConfig extends AuthorizationServerConfigurerAdapter {

    @Resource
    private TokenStore tokenStore;

    @Resource
    private RedisConnectionFactory redisConnectionFactory;

    @Resource
    private MyUserDetailsServiceImpl myUserDetailsService;

    @Resource
    private AuthenticationManager authenticationManager;


    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // 配置token获取和验证时的策略
        security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        /*
         * withClient 配置客户端id
         * secret 客户端密码，{noop}表示使用明文密码，不加密
         * accessTokenValiditySeconds： 配置token的有效期，单位为秒
         * refreshTokenValiditySeconds： 刷新token的时间，单位为秒
         */
        clients.inMemory()
                .withClient("seek")
                .authorizedGrantTypes("password", "authorization_code", "refresh_token")
                .authorities("ROLE_CLIENT")
                .scopes("read,write")
                .secret("{noop}123456")
                .accessTokenValiditySeconds(30*60)
                .refreshTokenValiditySeconds(30*60);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .authenticationManager(authenticationManager)
                .tokenStore(new RedisTokenStore(redisConnectionFactory))
                //不添加userDetailsService，刷新access_token时会报错
                .userDetailsService(myUserDetailsService);
    }

}
